package com.xul.crowd.controller;

import com.xul.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author xul
 * @create 2021-07-29 13:12
 */
@RestController
public class RedisController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 设置验证码手机号 验证码 超时时间到redis 让auth远程调用
     *
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     * @return
     */
    @RequestMapping("set/redis/key/value/remote/with/timeout")
    public ResultEntity<String> setRedisKeyValueRemoteWithTimeout(@RequestParam String key,
                                                                  @RequestParam String value,
                                                                  @RequestParam long time,
                                                                  @RequestParam TimeUnit timeUnit) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(key, value, time, timeUnit);
            return ResultEntity.successWithData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

    /**
     * 通过key(手机号拼接的字符串)从redis中查询验证码的信息 让auth远程调用
     *
     * @param key
     * @return
     */
    @RequestMapping("get/redis/string/value/by/key/remote")
    public ResultEntity<String> getRedisStringValueByKeyRemote(String key) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            String value = operations.get(key);
            return ResultEntity.successWithData(value);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

    /**
     * 通过key(手机号拼接的字符串)从redis中删除验证码的信息 让auth远程调用
     *
     * @param key
     * @return
     */
    @RequestMapping("remove/redis/key/remote")
    public ResultEntity<String> removeRedisKeyRemote(String key) {
        try {
            redisTemplate.delete(key);
            return ResultEntity.successWithData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }
}
